// src/composables/useEdit.ts
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { router } from '@/router/index'
import myaxios from '@/auth/auth.service'
import { useHome } from '@/components/composables/useHome'
import {showToastMessage} from "@/utils/message"

export interface CulturalRelicForm {
  name: string
  image: any[]
  dynasty: string
  country: string
  building_type: string
  other_building_type: string
  disease_types: string[]
  disease_image: any[]
  other_disease_types: string
  hasSpectrum: string
  hasThreeD: string
  spectrum_file: any[]
  threeD_file: any[]
  painting_theme: string
  painting_technique: string
  current_damage_status: string
  // 新增字段 👇
  pattern_types: string[]
  other_pattern_types: string
  composition_style: string[]
  other_composition_style: string
  dominant_colors: string[]
  other_dominant_colors: string
  human_pollution_details: string
  other_pollution_details: string
  disease_severity: string
  category_name: string
  category_id: number
}

export function useEdit() {
  const { choicesData } = useHome()
  const loading = ref(false)
  const error = ref('')
  const relicId = ref(0)
  const currentRelic = ref<any>({})
  const route = useRoute()
  const formRef = ref()
  const imageChanged = ref(false)
  // 表单数据模型
  const formData = reactive({
    culturalRelic: {
      name: '',
      image: [],
      dynasty: '',
      country: '',
      building_type: '',
      other_building_type: '',
      disease_types: [],
      other_disease_types: '',
      disease_image: [],
      hasSpectrum: 'false',
      hasThreeD: 'false',
      spectrum_file: [],
      threeD_file: [],
      painting_theme: '',
      painting_technique: '',
      current_damage_status: '',
      // 新增字段初始化 👇
      pattern_types: [],
      other_pattern_types: '',
      composition_style: [],
      other_composition_style: '',
      dominant_colors: [],
      other_dominant_colors: '',
      human_pollution_details: '',
      other_pollution_details: '',
      disease_severity: '',
      category_name: '',
      category_id: -1,
    } as CulturalRelicForm,
  })
  const goToUser = () => {
    router.push('/personalinfo')
  }
  const goToCategory = () => {
    router.push('/category')
  }

  const goTodetail = () => {
    router.push(`/relic-detail/${formData.culturalRelic.category_id}`)
  }

  const goHome = () => {
    router.push('/category')
  }
  const gomainpage = () => {
    router.push({
      path: '/mainpage',
      query: { categoryid: formData.culturalRelic.category_id, categoryname: formData.culturalRelic.category_name },
    })
  }
  /**
   * 将字符串解析为数组，并提取“其他:xxx”内容
   * @param value 字符串，如 "几何纹,其他:抽象图案"
   */
  const parseWithOther = (value: string, array: string[], otherField: string) => {
    if (!value) return
    const parts = value.split(',').map(s => s.trim()).filter(Boolean)
    array.length = 0
    let otherValue = ''
    parts.forEach(part => {
      if (part.startsWith('其他:')) {
        otherValue = part.slice(3)
        array.push('other')
        formData.culturalRelic[otherField as keyof CulturalRelicForm] = otherValue
      } else if (part.startsWith('人为污染:')) {
        otherValue = part.slice(5)
        formData.culturalRelic.human_pollution_details = otherValue
        array.push('人为污染')
      } else if (part.startsWith('其他污染:')) {
        otherValue = part.slice(5)
        formData.culturalRelic.other_pollution_details = otherValue
        array.push('其他污染')
      } else if (part.startsWith('其他')) {
        array.push('other')
      } else {
        array.push(part)
      }
    })
  }

  const handleDeleteImage = async (relicId, imageId) => {
    myaxios.deleteDiseaseImage(relicId, imageId).then((result) => {
      if (result.success) {
        location.reload()
      }
    })
  }

  const fetchRelicData = async () => {
    loading.value = true
    error.value = ''
    try {
      relicId.value = parseInt(route.params.id as string, 10)
      const response = await myaxios.fetchDetail(relicId.value)
      currentRelic.value = response.data
      const cr = formData.culturalRelic
      const d = currentRelic.value  //服务器数据

      cr.name = d.name || ''
      cr.dynasty = d.dynasty || ''
      cr.country = d.country || ''
      cr.building_type = d.building_type || ''
      cr.other_building_type = d.other_building_type || ''
      cr.hasSpectrum = d.hasSpectrum ? 'true' : 'false'
      cr.hasThreeD = d.hasThreeD ? 'true' : 'false'
      cr.painting_theme = d.painting_theme || ''
      cr.current_damage_status = d.current_damage_status || ''
      cr.disease_severity = d.disease_severity || ''
      cr.hasSpectrum = d.hasSpectrum ? 'true' : 'false'
      cr.hasThreeD = d.hasThreeD ? 'true' : 'false'// 示例：在 fetchRelicData 成功后
      cr.category_name = d.category.name || ''
      cr.category_id = d.category.id || -1
      cr.disease_image = d.disease_images.map(img => ({
        id: img.id,
        url: img.image_base64 || img.image_url,
        image_name: img.image_name || '未命名',
        description: img.image_description || '',
        created_at: img.created_at || '',
        file: null, // 服务器图片无 raw file
      }))

      // 彩画做法
      cr.painting_technique = d.painting_technique || ''

      // 解析复合字段
      parseWithOther(d.pattern_types, cr.pattern_types, 'other_pattern_types')
      parseWithOther(d.composition_style, cr.composition_style, 'other_composition_style')
      parseWithOther(d.dominant_colors, cr.dominant_colors, 'other_dominant_colors')
      parseWithOther(d.disease_types, cr.disease_types, 'other_disease_types')

    } catch (e) {
      error.value = '加载失败'
      console.error(e)
    } finally {
      loading.value = false
    }
  }

  const validateWithOther = (
    selected: string[],
    otherValue: string,
    fieldName: string
  ): boolean => {
    if (!Array.isArray(selected)) return false
    if (selected.includes('other') && !otherValue?.trim()) {
      const msg=`请选择“${fieldName}”中的“其他”后填写具体内容`
      showToastMessage("warning",msg)
      return false
    }
    return true
  }

  const validateDiseaseTypes = (): boolean => {
    const { culturalRelic } = formData
    if (culturalRelic.disease_types.length === 0) {
      showToastMessage("warning","请选择至少一种病害类型")
      return false
    }
    if (culturalRelic.disease_types.includes('人为污染') && !culturalRelic.human_pollution_details?.trim()) {
      showToastMessage("warning","请详细描述“人为污染”的情况")
      return false
    }
    if (culturalRelic.disease_types.includes('其他污染') && !culturalRelic.other_pollution_details?.trim()) {
      showToastMessage("warning","请详细描述“其他污染”的情况")
      return false
    }
    return true
  }

  const validateComplexFields = (): boolean => {
    const { culturalRelic } = formData
    if (!validateDiseaseTypes()) return false
    if (!validateWithOther(culturalRelic.pattern_types, culturalRelic.other_pattern_types, '纹样类型')) return false
    if (!validateWithOther(culturalRelic.composition_style, culturalRelic.other_composition_style, '构图形式')) return false
    if (!validateWithOther(culturalRelic.dominant_colors, culturalRelic.other_dominant_colors, '主色调')) return false
    return true
  }

  const onImageChange = () => {
    imageChanged.value = true
  }

  const onClickLeft = () => {
    router.go(-1)
  }

  const handleCancel = () => {
    router.go(-1)
  }

  const onFailed = () => {
    showToastMessage("error","请完善必填信息")
  }

  const getRawFile = (fileItem: any): File | null => {
    return fileItem?.file || fileItem?.raw || (fileItem instanceof File ? fileItem : null)
  }

  const onSubmit = async () => {
    console.log('上传前数据', formData.culturalRelic)
    if (loading.value || !relicId.value) {
      console.log('1')
      return
    }
    if (!validateComplexFields()) {
      console.log('2')
      return
    }

    console.log('3')
    try {
      loading.value = true
      const f = formData.culturalRelic

      const form = new FormData()

      form.append('name', f.name)
      form.append('hasSpectrum', f.hasSpectrum)
      form.append('hasThreeD', f.hasThreeD)
      form.append('painting_theme', f.painting_theme)
      form.append('current_damage_status', f.current_damage_status)
      form.append('painting_technique', f.painting_technique)
      form.append('disease_severity', f.disease_severity)

      // 拼接复合字段
      const formatWithOther = (selected: string[], other: string, label: string) => {
        return selected.map(item => {
          if (item === 'other') return other ? `${label}:${other}` : label
          return item
        }).join(',')
      }

      form.append('pattern_types', formatWithOther(f.pattern_types, f.other_pattern_types, '其他'))
      form.append('composition_style', formatWithOther(f.composition_style, f.other_composition_style, '其他'))
      form.append('dominant_colors', formatWithOther(f.dominant_colors, f.other_dominant_colors, '其他'))

      // 特殊处理病害类型
      const diseaseParts: string[] = []
      f.disease_types.forEach(type => {
        if (type === '人为污染') {
          const detail = f.human_pollution_details?.trim()
          diseaseParts.push(detail ? `人为污染:${detail}` : '人为污染')
        } else if (type === '其他污染') {
          const detail = f.other_pollution_details?.trim()
          diseaseParts.push(detail ? `其他污染:${detail}` : '其他污染')
        } else if (type === 'other') {
          const other = f.other_disease_types?.trim()
          diseaseParts.push(other ? `其他:${other}` : '其他')
        } else {
          diseaseParts.push(type)
        }
      })
      form.append('disease_types', diseaseParts.join(','))

      // 图像上传
      if (f.image.length > 0 && f.image[0].raw) {
        form.append('image', f.image[0].raw)
      }

      // --- 病害图像（批量）---
      const diseaseImageMetadatas = []

      if (Array.isArray(f.disease_image)) {
        console.log('1 - 开始处理病害图像列表，共:', f.disease_image.length, '项')

        for (let i = 0; i < f.disease_image.length; i++) {
          const item = f.disease_image[i]
          console.log('item:', item.id)
          const rawFile = getRawFile(item)

          // 为每个条目生成唯一 file_key，用于关联文件和元数据
          const fileKey = `disease_image_file_${item.id || `new_${i}`}`
          console.log('fileKey:', fileKey)

          // 构建元数据
          const metadata = {
            id: item.id || null,
            name: item.customName || item.image_name || '未命名',
            description: item.description || '',
            has_new_file: false,
            file_key: "" // 默认无文件
          }
          console.log('metadata:', metadata)
          // 如果有新文件，上传并记录 file_key
          if (rawFile instanceof File) {
            console.log(`2 - 发现新文件，准备上传 [${i}]:`, rawFile.name)
            form.append(fileKey, rawFile) // 使用唯一 key 上传
            metadata.has_new_file = true
            metadata.file_key = fileKey // 告诉后端这个元数据对应的文件字段名
          }
          // 否则 file_key 保持 null，表示无新文件

          diseaseImageMetadatas.push(metadata)
        }
      }

      // ✅ 发送元数据（包含 file_key 和 has_new_file）
      if (diseaseImageMetadatas.length > 0) {
        console.log('4 - 发送元数据（含 file_key）:', diseaseImageMetadatas)
        form.append('disease_image_metadata', JSON.stringify(diseaseImageMetadatas))
      }


      if (f.spectrum_file.length > 0 && f.spectrum_file[0].raw) {
        form.append('spectrum_file', f.spectrum_file[0].raw)
      }
      if (f.threeD_file.length > 0 && f.threeD_file[0].raw) {
        form.append('threeD_file', f.threeD_file[0].raw)
      }


      // ✅ 在这里打印 form 的真实内容
      console.log('--- 即将提交的表单数据 ---')
      for (let [key, value] of form.entries()) {
        if (typeof value === 'object' && value instanceof File) {
          console.log(key, '=', value.name, '(File)')
        } else {
          console.log(key, '=', value)
        }
      }


      const response = await myaxios.updateRelic(relicId.value, form)
      showToastMessage("success","更新成功")
      router.push(`/relic-detail/${relicId.value}`)
    } catch (e) {
      console.error('更新失败:', e)
      showToastMessage("error","更新失败，请重试")
    } finally {
      loading.value = false
    }
  }

  onMounted(() => {
    fetchRelicData()
  })

  return {
    choicesData,
    loading,
    error,
    relicId,
    currentRelic,
    formRef,
    formData,
    imageChanged,
    goHome,
    goToUser,
    goToCategory,
    goTodetail,
    gomainpage,
    validateComplexFields,
    onImageChange,
    onFailed,
    fetchRelicData,
    onClickLeft,
    onSubmit,
    handleCancel,
    handleDeleteImage,
  }
}
